<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Performing raw SQL queries &mdash; Django 1.7.8.dev20150401230226 documentation</title>
    
    <link rel="stylesheet" href="../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../../',
        VERSION:     '1.7.8.dev20150401230226',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../_static/underscore.js"></script>
    <script type="text/javascript" src="../../_static/doctools.js"></script>
    <link rel="top" title="Django 1.7.8.dev20150401230226 documentation" href="../../index.html" />
    <link rel="up" title="Models and databases" href="index.html" />
    <link rel="next" title="Database transactions" href="transactions.html" />
    <link rel="prev" title="Managers" href="managers.html" />



 
<script type="text/javascript" src="../../templatebuiltins.js"></script>
<script type="text/javascript">
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);
</script>


  </head>
  <body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../../index.html">Django 1.7.8.dev20150401230226 documentation</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../../index.html">Home</a>  |
        <a title="Table of contents" href="../../contents.html">Table of contents</a>  |
        <a title="Global index" href="../../genindex.html">Index</a>  |
        <a title="Module index" href="../../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="managers.html" title="Managers">previous</a>
     |
    <a href="../index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="transactions.html" title="Database transactions">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="topics-db-sql">
            
  <div class="section" id="s-performing-raw-sql-queries">
<span id="performing-raw-sql-queries"></span><h1>Performing raw SQL queries<a class="headerlink" href="#performing-raw-sql-queries" title="Permalink to this headline">¶</a></h1>
<p>When the <a class="reference internal" href="queries.html"><em>model query APIs</em></a> don&#8217;t go far enough, you
can fall back to writing raw SQL. Django gives you two ways of performing raw
SQL queries: you can use <a class="reference internal" href="#django.db.models.Manager.raw" title="django.db.models.Manager.raw"><tt class="xref py py-meth docutils literal"><span class="pre">Manager.raw()</span></tt></a> to <a class="reference internal" href="#performing-raw-queries">perform raw queries and
return model instances</a>, or you can avoid the model layer entirely and
<a class="reference internal" href="#executing-custom-sql-directly">execute custom SQL directly</a>.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">You should be very careful whenever you write raw SQL. Every time you use
it, you should properly escape any parameters that the user can control
by using <tt class="docutils literal"><span class="pre">params</span></tt> in order to protect against SQL injection attacks.
Please read more about <a class="reference internal" href="../security.html#sql-injection-protection"><em>SQL injection protection</em></a>.</p>
</div>
<div class="section" id="s-performing-raw-queries">
<span id="s-executing-raw-queries"></span><span id="performing-raw-queries"></span><span id="executing-raw-queries"></span><h2>Performing raw queries<a class="headerlink" href="#performing-raw-queries" title="Permalink to this headline">¶</a></h2>
<p>The <tt class="docutils literal"><span class="pre">raw()</span></tt> manager method can be used to perform raw SQL queries that
return model instances:</p>
<dl class="method">
<dt id="django.db.models.Manager.raw">
<tt class="descclassname">Manager.</tt><tt class="descname">raw</tt>(<em>raw_query</em>, <em>params=None</em>, <em>translations=None</em>)<a class="headerlink" href="#django.db.models.Manager.raw" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>This method takes a raw SQL query, executes it, and returns a
<tt class="docutils literal"><span class="pre">django.db.models.query.RawQuerySet</span></tt> instance. This <tt class="docutils literal"><span class="pre">RawQuerySet</span></tt> instance
can be iterated over just like a normal
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><tt class="xref py py-class docutils literal"><span class="pre">QuerySet</span></tt></a> to provide object instances.</p>
<p>This is best illustrated with an example. Suppose you have the following model:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Person</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">first_name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="o">...</span><span class="p">)</span>
    <span class="n">last_name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="o">...</span><span class="p">)</span>
    <span class="n">birth_date</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">DateField</span><span class="p">(</span><span class="o">...</span><span class="p">)</span>
</pre></div>
</div>
<p>You could then execute custom SQL like so:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">p</span> <span class="ow">in</span> <span class="n">Person</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">raw</span><span class="p">(</span><span class="s">&#39;SELECT * FROM myapp_person&#39;</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">print</span><span class="p">(</span><span class="n">p</span><span class="p">)</span>
<span class="go">John Smith</span>
<span class="go">Jane Jones</span>
</pre></div>
</div>
<p>Of course, this example isn&#8217;t very exciting &#8211; it&#8217;s exactly the same as
running <tt class="docutils literal"><span class="pre">Person.objects.all()</span></tt>. However, <tt class="docutils literal"><span class="pre">raw()</span></tt> has a bunch of other
options that make it very powerful.</p>
<div class="admonition-model-table-names admonition">
<p class="first admonition-title">Model table names</p>
<p>Where did the name of the <tt class="docutils literal"><span class="pre">Person</span></tt> table come from in that example?</p>
<p>By default, Django figures out a database table name by joining the
model&#8217;s &#8220;app label&#8221; &#8211; the name you used in <tt class="docutils literal"><span class="pre">manage.py</span> <span class="pre">startapp</span></tt> &#8211; to
the model&#8217;s class name, with an underscore between them. In the example
we&#8217;ve assumed that the <tt class="docutils literal"><span class="pre">Person</span></tt> model lives in an app named <tt class="docutils literal"><span class="pre">myapp</span></tt>,
so its table would be <tt class="docutils literal"><span class="pre">myapp_person</span></tt>.</p>
<p class="last">For more details check out the documentation for the
<a class="reference internal" href="../../ref/models/options.html#django.db.models.Options.db_table" title="django.db.models.Options.db_table"><tt class="xref py py-attr docutils literal"><span class="pre">db_table</span></tt></a> option, which also lets you manually set the
database table name.</p>
</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">No checking is done on the SQL statement that is passed in to <tt class="docutils literal"><span class="pre">.raw()</span></tt>.
Django expects that the statement will return a set of rows from the
database, but does nothing to enforce that. If the query does not
return rows, a (possibly cryptic) error will result.</p>
</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">If you are performing queries on MySQL, note that MySQL&#8217;s silent type coercion
may cause unexpected results when mixing types. If you query on a string
type column, but with an integer value, MySQL will coerce the types of all values
in the table to an integer before performing the comparison. For example, if your
table contains the values <tt class="docutils literal"><span class="pre">'abc'</span></tt>, <tt class="docutils literal"><span class="pre">'def'</span></tt> and you query for <tt class="docutils literal"><span class="pre">WHERE</span> <span class="pre">mycolumn=0</span></tt>,
both rows will match. To prevent this, perform the correct typecasting
before using the value in a query.</p>
</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">While a <tt class="docutils literal"><span class="pre">RawQuerySet</span></tt> instance can be iterated over like a normal
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><tt class="xref py py-class docutils literal"><span class="pre">QuerySet</span></tt></a>, <tt class="docutils literal"><span class="pre">RawQuerySet</span></tt> doesn&#8217;t
implement all methods you can use with <tt class="docutils literal"><span class="pre">QuerySet</span></tt>. For example,
<tt class="docutils literal"><span class="pre">__bool__()</span></tt> and <tt class="docutils literal"><span class="pre">__len__()</span></tt> are not defined in <tt class="docutils literal"><span class="pre">RawQuerySet</span></tt>, and
thus all <tt class="docutils literal"><span class="pre">RawQuerySet</span></tt> instances are considered <tt class="docutils literal"><span class="pre">True</span></tt>. The reason
these methods are not implemented in <tt class="docutils literal"><span class="pre">RawQuerySet</span></tt> is that implementing
them without internal caching would be a performance drawback and adding
such caching would be backward incompatible.</p>
</div>
<div class="section" id="s-mapping-query-fields-to-model-fields">
<span id="mapping-query-fields-to-model-fields"></span><h3>Mapping query fields to model fields<a class="headerlink" href="#mapping-query-fields-to-model-fields" title="Permalink to this headline">¶</a></h3>
<p><tt class="docutils literal"><span class="pre">raw()</span></tt> automatically maps fields in the query to fields on the model.</p>
<p>The order of fields in your query doesn&#8217;t matter. In other words, both
of the following queries work identically:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Person</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">raw</span><span class="p">(</span><span class="s">&#39;SELECT id, first_name, last_name, birth_date FROM myapp_person&#39;</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Person</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">raw</span><span class="p">(</span><span class="s">&#39;SELECT last_name, birth_date, first_name, id FROM myapp_person&#39;</span><span class="p">)</span>
<span class="gp">...</span>
</pre></div>
</div>
<p>Matching is done by name. This means that you can use SQL&#8217;s <tt class="docutils literal"><span class="pre">AS</span></tt> clauses to
map fields in the query to model fields. So if you had some other table that
had <tt class="docutils literal"><span class="pre">Person</span></tt> data in it, you could easily map it into <tt class="docutils literal"><span class="pre">Person</span></tt> instances:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Person</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">raw</span><span class="p">(</span><span class="s">&#39;&#39;&#39;SELECT first AS first_name,</span>
<span class="gp">... </span><span class="s">                             last AS last_name,</span>
<span class="gp">... </span><span class="s">                             bd AS birth_date,</span>
<span class="gp">... </span><span class="s">                             pk AS id,</span>
<span class="gp">... </span><span class="s">                      FROM some_other_table&#39;&#39;&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>As long as the names match, the model instances will be created correctly.</p>
<p>Alternatively, you can map fields in the query to model fields using the
<tt class="docutils literal"><span class="pre">translations</span></tt> argument to <tt class="docutils literal"><span class="pre">raw()</span></tt>. This is a dictionary mapping names of
fields in the query to names of fields on the model. For example, the above
query could also be written:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">name_map</span> <span class="o">=</span> <span class="p">{</span><span class="s">&#39;first&#39;</span><span class="p">:</span> <span class="s">&#39;first_name&#39;</span><span class="p">,</span> <span class="s">&#39;last&#39;</span><span class="p">:</span> <span class="s">&#39;last_name&#39;</span><span class="p">,</span> <span class="s">&#39;bd&#39;</span><span class="p">:</span> <span class="s">&#39;birth_date&#39;</span><span class="p">,</span> <span class="s">&#39;pk&#39;</span><span class="p">:</span> <span class="s">&#39;id&#39;</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Person</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">raw</span><span class="p">(</span><span class="s">&#39;SELECT * FROM some_other_table&#39;</span><span class="p">,</span> <span class="n">translations</span><span class="o">=</span><span class="n">name_map</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="s-index-lookups">
<span id="index-lookups"></span><h3>Index lookups<a class="headerlink" href="#index-lookups" title="Permalink to this headline">¶</a></h3>
<p><tt class="docutils literal"><span class="pre">raw()</span></tt> supports indexing, so if you need only the first result you can
write:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">first_person</span> <span class="o">=</span> <span class="n">Person</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">raw</span><span class="p">(</span><span class="s">&#39;SELECT * FROM myapp_person&#39;</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span>
</pre></div>
</div>
<p>However, the indexing and slicing are not performed at the database level. If
you have a large number of <tt class="docutils literal"><span class="pre">Person</span></tt> objects in your database, it is more
efficient to limit the query at the SQL level:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">first_person</span> <span class="o">=</span> <span class="n">Person</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">raw</span><span class="p">(</span><span class="s">&#39;SELECT * FROM myapp_person LIMIT 1&#39;</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span>
</pre></div>
</div>
</div>
<div class="section" id="s-deferring-model-fields">
<span id="deferring-model-fields"></span><h3>Deferring model fields<a class="headerlink" href="#deferring-model-fields" title="Permalink to this headline">¶</a></h3>
<p>Fields may also be left out:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">people</span> <span class="o">=</span> <span class="n">Person</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">raw</span><span class="p">(</span><span class="s">&#39;SELECT id, first_name FROM myapp_person&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>The <tt class="docutils literal"><span class="pre">Person</span></tt> objects returned by this query will be deferred model instances
(see <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.defer" title="django.db.models.query.QuerySet.defer"><tt class="xref py py-meth docutils literal"><span class="pre">defer()</span></tt></a>). This means that the
fields that are omitted from the query will be loaded on demand. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">p</span> <span class="ow">in</span> <span class="n">Person</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">raw</span><span class="p">(</span><span class="s">&#39;SELECT id, first_name FROM myapp_person&#39;</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">print</span><span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">first_name</span><span class="p">,</span> <span class="c"># This will be retrieved by the original query</span>
<span class="gp">... </span>          <span class="n">p</span><span class="o">.</span><span class="n">last_name</span><span class="p">)</span> <span class="c"># This will be retrieved on demand</span>
<span class="gp">...</span>
<span class="go">John Smith</span>
<span class="go">Jane Jones</span>
</pre></div>
</div>
<p>From outward appearances, this looks like the query has retrieved both
the first name and last name. However, this example actually issued 3
queries. Only the first names were retrieved by the raw() query &#8211; the
last names were both retrieved on demand when they were printed.</p>
<p>There is only one field that you can&#8217;t leave out - the primary key
field. Django uses the primary key to identify model instances, so it
must always be included in a raw query. An <tt class="docutils literal"><span class="pre">InvalidQuery</span></tt> exception
will be raised if you forget to include the primary key.</p>
</div>
<div class="section" id="s-adding-annotations">
<span id="adding-annotations"></span><h3>Adding annotations<a class="headerlink" href="#adding-annotations" title="Permalink to this headline">¶</a></h3>
<p>You can also execute queries containing fields that aren&#8217;t defined on the
model. For example, we could use <a class="reference external" href="http://www.postgresql.org/docs/current/static/functions-datetime.html">PostgreSQL&#8217;s age() function</a> to get a list
of people with their ages calculated by the database:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">people</span> <span class="o">=</span> <span class="n">Person</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">raw</span><span class="p">(</span><span class="s">&#39;SELECT *, age(birth_date) AS age FROM myapp_person&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">p</span> <span class="ow">in</span> <span class="n">people</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">print</span><span class="p">(</span><span class="s">&quot;</span><span class="si">%s</span><span class="s"> is </span><span class="si">%s</span><span class="s">.&quot;</span> <span class="o">%</span> <span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">first_name</span><span class="p">,</span> <span class="n">p</span><span class="o">.</span><span class="n">age</span><span class="p">))</span>
<span class="go">John is 37.</span>
<span class="go">Jane is 42.</span>
<span class="gp">...</span>
</pre></div>
</div>
</div>
<div class="section" id="s-passing-parameters-into-raw">
<span id="passing-parameters-into-raw"></span><h3>Passing parameters into <tt class="docutils literal"><span class="pre">raw()</span></tt><a class="headerlink" href="#passing-parameters-into-raw" title="Permalink to this headline">¶</a></h3>
<p>If you need to perform parameterized queries, you can use the <tt class="docutils literal"><span class="pre">params</span></tt>
argument to <tt class="docutils literal"><span class="pre">raw()</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">lname</span> <span class="o">=</span> <span class="s">&#39;Doe&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Person</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">raw</span><span class="p">(</span><span class="s">&#39;SELECT * FROM myapp_person WHERE last_name = </span><span class="si">%s</span><span class="s">&#39;</span><span class="p">,</span> <span class="p">[</span><span class="n">lname</span><span class="p">])</span>
</pre></div>
</div>
<p><tt class="docutils literal"><span class="pre">params</span></tt> is a list or dictionary of parameters. You&#8217;ll use <tt class="docutils literal"><span class="pre">%s</span></tt>
placeholders in the query string for a list, or <tt class="docutils literal"><span class="pre">%(key)s</span></tt>
placeholders for a dictionary (where <tt class="docutils literal"><span class="pre">key</span></tt> is replaced by a
dictionary key, of course), regardless of your database engine.  Such
placeholders will be replaced with parameters from the <tt class="docutils literal"><span class="pre">params</span></tt>
argument.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Dictionary params are not supported with the SQLite backend; with
this backend, you must pass parameters as a list.</p>
</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p><strong>Do not use string formatting on raw queries!</strong></p>
<p>It&#8217;s tempting to write the above query as:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">query</span> <span class="o">=</span> <span class="s">&#39;SELECT * FROM myapp_person WHERE last_name = </span><span class="si">%s</span><span class="s">&#39;</span> <span class="o">%</span> <span class="n">lname</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Person</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">raw</span><span class="p">(</span><span class="n">query</span><span class="p">)</span>
</pre></div>
</div>
<p><strong>Don&#8217;t.</strong></p>
<p class="last">Using the <tt class="docutils literal"><span class="pre">params</span></tt> argument completely protects you from <a class="reference external" href="http://en.wikipedia.org/wiki/SQL_injection">SQL injection
attacks</a>, a common exploit where attackers inject arbitrary SQL into
your database. If you use string interpolation, sooner or later you&#8217;ll
fall victim to SQL injection. As long as you remember to always use the
<tt class="docutils literal"><span class="pre">params</span></tt> argument you&#8217;ll be protected.</p>
</div>
<div class="versionchanged">
<span class="title">Changed in Django 1.6:</span> <p>In Django 1.5 and earlier, you could pass parameters as dictionaries
when using PostgreSQL or MySQL, although this wasn&#8217;t documented. Now
you can also do this when using Oracle, and it is officially supported.</p>
</div>
</div>
</div>
<div class="section" id="s-executing-custom-sql-directly">
<span id="s-executing-custom-sql"></span><span id="executing-custom-sql-directly"></span><span id="executing-custom-sql"></span><h2>Executing custom SQL directly<a class="headerlink" href="#executing-custom-sql-directly" title="Permalink to this headline">¶</a></h2>
<p>Sometimes even <a class="reference internal" href="#django.db.models.Manager.raw" title="django.db.models.Manager.raw"><tt class="xref py py-meth docutils literal"><span class="pre">Manager.raw()</span></tt></a> isn&#8217;t quite enough: you might need to
perform queries that don&#8217;t map cleanly to models, or directly execute
<tt class="docutils literal"><span class="pre">UPDATE</span></tt>, <tt class="docutils literal"><span class="pre">INSERT</span></tt>, or <tt class="docutils literal"><span class="pre">DELETE</span></tt> queries.</p>
<p>In these cases, you can always access the database directly, routing around
the model layer entirely.</p>
<p>The object <tt class="docutils literal"><span class="pre">django.db.connection</span></tt> represents the default database
connection. To use the database connection, call <tt class="docutils literal"><span class="pre">connection.cursor()</span></tt> to
get a cursor object. Then, call <tt class="docutils literal"><span class="pre">cursor.execute(sql,</span> <span class="pre">[params])</span></tt> to execute
the SQL and <tt class="docutils literal"><span class="pre">cursor.fetchone()</span></tt> or <tt class="docutils literal"><span class="pre">cursor.fetchall()</span></tt> to return the
resulting rows.</p>
<p>For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">connection</span>

<span class="k">def</span> <span class="nf">my_custom_sql</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
    <span class="n">cursor</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>

    <span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;UPDATE bar SET foo = 1 WHERE baz = </span><span class="si">%s</span><span class="s">&quot;</span><span class="p">,</span> <span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">baz</span><span class="p">])</span>

    <span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;SELECT foo FROM bar WHERE baz = </span><span class="si">%s</span><span class="s">&quot;</span><span class="p">,</span> <span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">baz</span><span class="p">])</span>
    <span class="n">row</span> <span class="o">=</span> <span class="n">cursor</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()</span>

    <span class="k">return</span> <span class="n">row</span>
</pre></div>
</div>
<div class="versionchanged">
<span class="title">Changed in Django 1.6:</span> <p>In Django 1.5 and earlier, after performing a data changing operation, you
had to call <tt class="docutils literal"><span class="pre">transaction.commit_unless_managed()</span></tt> to ensure your changes
were committed to the database. Since Django now defaults to database-level
autocommit, this isn&#8217;t necessary any longer.</p>
</div>
<p>Note that if you want to include literal percent signs in the query, you have to
double them in the case you are passing parameters:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;SELECT foo FROM bar WHERE baz = &#39;30%&#39;&quot;</span><span class="p">)</span>
<span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;SELECT foo FROM bar WHERE baz = &#39;30</span><span class="si">%%</span><span class="s">&#39; AND id = </span><span class="si">%s</span><span class="s">&quot;</span><span class="p">,</span> <span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">id</span><span class="p">])</span>
</pre></div>
</div>
<p>If you are using <a class="reference internal" href="multi-db.html"><em>more than one database</em></a>, you can
use <tt class="docutils literal"><span class="pre">django.db.connections</span></tt> to obtain the connection (and cursor) for a
specific database. <tt class="docutils literal"><span class="pre">django.db.connections</span></tt> is a dictionary-like
object that allows you to retrieve a specific connection using its
alias:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">connections</span>
<span class="n">cursor</span> <span class="o">=</span> <span class="n">connections</span><span class="p">[</span><span class="s">&#39;my_db_alias&#39;</span><span class="p">]</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
<span class="c"># Your code here...</span>
</pre></div>
</div>
<p>By default, the Python DB API will return results without their field
names, which means you end up with a <tt class="docutils literal"><span class="pre">list</span></tt> of values, rather than a
<tt class="docutils literal"><span class="pre">dict</span></tt>. At a small performance cost, you can return results as a
<tt class="docutils literal"><span class="pre">dict</span></tt> by using something like this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">dictfetchall</span><span class="p">(</span><span class="n">cursor</span><span class="p">):</span>
    <span class="s">&quot;Returns all rows from a cursor as a dict&quot;</span>
    <span class="n">desc</span> <span class="o">=</span> <span class="n">cursor</span><span class="o">.</span><span class="n">description</span>
    <span class="k">return</span> <span class="p">[</span>
        <span class="nb">dict</span><span class="p">(</span><span class="nb">zip</span><span class="p">([</span><span class="n">col</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="k">for</span> <span class="n">col</span> <span class="ow">in</span> <span class="n">desc</span><span class="p">],</span> <span class="n">row</span><span class="p">))</span>
        <span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">cursor</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>
    <span class="p">]</span>
</pre></div>
</div>
<p>Here is an example of the difference between the two:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;SELECT id, parent_id FROM test LIMIT 2&quot;</span><span class="p">);</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cursor</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>
<span class="go">((54360982L, None), (54360880L, None))</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s">&quot;SELECT id, parent_id FROM test LIMIT 2&quot;</span><span class="p">);</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">dictfetchall</span><span class="p">(</span><span class="n">cursor</span><span class="p">)</span>
<span class="go">[{&#39;parent_id&#39;: None, &#39;id&#39;: 54360982L}, {&#39;parent_id&#39;: None, &#39;id&#39;: 54360880L}]</span>
</pre></div>
</div>
<div class="section" id="s-connections-and-cursors">
<span id="connections-and-cursors"></span><h3>Connections and cursors<a class="headerlink" href="#connections-and-cursors" title="Permalink to this headline">¶</a></h3>
<p><tt class="docutils literal"><span class="pre">connection</span></tt> and <tt class="docutils literal"><span class="pre">cursor</span></tt> mostly implement the standard Python DB-API
described in <span class="target" id="index-0"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0249"><strong>PEP 249</strong></a> — except when it comes to <a class="reference internal" href="transactions.html"><em>transaction handling</em></a>.</p>
<p>If you&#8217;re not familiar with the Python DB-API, note that the SQL statement in
<tt class="docutils literal"><span class="pre">cursor.execute()</span></tt> uses placeholders, <tt class="docutils literal"><span class="pre">&quot;%s&quot;</span></tt>, rather than adding
parameters directly within the SQL. If you use this technique, the underlying
database library will automatically escape your parameters as necessary.</p>
<p>Also note that Django expects the <tt class="docutils literal"><span class="pre">&quot;%s&quot;</span></tt> placeholder, <em>not</em> the <tt class="docutils literal"><span class="pre">&quot;?&quot;</span></tt>
placeholder, which is used by the SQLite Python bindings. This is for the sake
of consistency and sanity.</p>
<div class="versionchanged">
<span class="title">Changed in Django 1.7.</span> </div>
<p><span class="target" id="index-1"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0249"><strong>PEP 249</strong></a> does not state whether a cursor should be usable as a context
manager. Prior to Python 2.7, a cursor was usable as a context manager due
an unexpected behavior in magic method lookups (<a class="reference external" href="http://bugs.python.org/issue9220">Python ticket #9220</a>).
Django 1.7 explicitly added support to allow using a cursor as context
manager.</p>
<p>Using a cursor as a context manager:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">with</span> <span class="n">connection</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span> <span class="k">as</span> <span class="n">c</span><span class="p">:</span>
    <span class="n">c</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="o">...</span><span class="p">)</span>
</pre></div>
</div>
<p>is equivalent to:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">c</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
<span class="k">try</span><span class="p">:</span>
    <span class="n">c</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="o">...</span><span class="p">)</span>
<span class="k">finally</span><span class="p">:</span>
    <span class="n">c</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Performing raw SQL queries</a><ul>
<li><a class="reference internal" href="#performing-raw-queries">Performing raw queries</a><ul>
<li><a class="reference internal" href="#mapping-query-fields-to-model-fields">Mapping query fields to model fields</a></li>
<li><a class="reference internal" href="#index-lookups">Index lookups</a></li>
<li><a class="reference internal" href="#deferring-model-fields">Deferring model fields</a></li>
<li><a class="reference internal" href="#adding-annotations">Adding annotations</a></li>
<li><a class="reference internal" href="#passing-parameters-into-raw">Passing parameters into <tt class="docutils literal"><span class="pre">raw()</span></tt></a></li>
</ul>
</li>
<li><a class="reference internal" href="#executing-custom-sql-directly">Executing custom SQL directly</a><ul>
<li><a class="reference internal" href="#connections-and-cursors">Connections and cursors</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h3>Browse</h3>
  <ul>
    
      <li>Prev: <a href="managers.html">Managers</a></li>
    
    
      <li>Next: <a href="transactions.html">Database transactions</a></li>
    
  </ul>
  <h3>You are here:</h3>
  <ul>
      <li>
        <a href="../../index.html">Django 1.7.8.dev20150401230226 documentation</a>
        
          <ul><li><a href="../index.html">Using Django</a>
        
          <ul><li><a href="index.html">Models and databases</a>
        
        <ul><li>Performing raw SQL queries</li></ul>
        </li></ul></li></ul>
      </li>
  </ul>

  <h3>This Page</h3>
  <ul class="this-page-menu">
    <li><a href="../../_sources/topics/db/sql.txt"
           rel="nofollow">Show Source</a></li>
  </ul>
<div id="searchbox" style="display: none">
  <h3>Quick search</h3>
    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    <p class="searchtip" style="font-size: 90%">
    Enter search terms or a module, class or function name.
    </p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">Apr 02, 2015</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="managers.html" title="Managers">previous</a>
     |
    <a href="../index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="transactions.html" title="Database transactions">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>